package com.zhiwang.xiaoqu.viewmodel

import android.app.Application
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Network
import android.os.Build
import android.provider.Settings
import com.zhiwang.xiaoqu.bus.NetWorkConnectedEvent
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject

class NetWorkViewModel @Inject constructor(var appContext: Application) {
    companion object {
        var connected: Boolean = false
    }

    private val connectivityManager: ConnectivityManager
        get() {
            val cm = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            return cm
        }
    private val connectivityReceiver: BroadcastReceiver?
        get() {
            var value: BroadcastReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context?, intent: Intent?) {
                    val activeNetworkInfo = connectivityManager.activeNetworkInfo
                    val b = if (activeNetworkInfo == null) false else activeNetworkInfo.isConnected

                    val oldConnc = connected

                    connected = b

                    if (oldConnc.not() && b) {
                        EventBus.getDefault().post(NetWorkConnectedEvent())
                    }
                }
            }
            return value
        }
    val TAG = "NetWorkViewModel"

    init {
        init()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            connectivityManager.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {

                override fun onAvailable(network: Network?) {
                    if (connected.not()) {
                        connected = true
                        EventBus.getDefault().post(NetWorkConnectedEvent())
                    }
                    connected = true
                }

                override fun onLost(network: Network?) {
                    connected = false
                }
            })
        }
//        }
        else {
            val intentFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
            appContext.registerReceiver(connectivityReceiver, intentFilter)

        }
    }


    private fun init() {
        val cm = connectivityManager
        connected = cm.activeNetworkInfo != null
                && cm.activeNetworkInfo.isConnected

    }

    fun checkSetting() {
        appContext.startActivity(
            Intent(Settings.ACTION_WIRELESS_SETTINGS)
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        )
    }

    fun dispose() {
        appContext.unregisterReceiver(connectivityReceiver)
    }

}